package com.scott.netty.echo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @author Scott 2017/12/12 15:44
 */
public class DiscardClientHandler extends ChannelInboundHandlerAdapter {
    private final ByteBuf firstMessage;

    public DiscardClientHandler() {

        byte[] message = "你好".getBytes();
        firstMessage = Unpooled.buffer(message.length);

        for (int i = 0; i < message.length; i++) {
            firstMessage.writeByte(message[i]);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(firstMessage);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ctx.write(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }
}
